package com.lq.controller;

import com.auth0.jwt.JWT;
import com.lq.CodeEnnms.ApiResponseEnum;
import com.lq.pojo.ApiResponse;
import com.lq.pojo.Users;
import com.lq.service.ItokenUserService;
import com.lq.util.ApiResponseUtil;
import com.lq.util.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

@Controller
public class TokenLoginConteoller {

    @Autowired
    private ItokenUserService userService;

    @RequestMapping(value = "/liulogins",method = RequestMethod.POST)
    @ResponseBody
    public ApiResponse login(String loginName, String password, HttpServletResponse response, HttpServletRequest request){
        System.out.println(loginName+":"+password);
        //身份验证是否成功
        boolean isSuccess = userService.checkUser(loginName, password);
        System.out.println("是否验证成功:"+isSuccess);
        if(isSuccess){
            Users users=userService.getUserByLoginName(loginName);
            if(users!=null){
                //返回token
                String token= JwtUtil.sign(users.getName(),users.getId());
                if(token!=null){
                    response.setHeader("Access-Control-Expose-Headers","Cache-Control,Content-Type,Expires,Pragma,Content-Language,Last-Modified,token");
                    response.setHeader("token",token); //设置响应头

                    return ApiResponseUtil.getApiResponse(token);
                }
            }
        }
        //返回登录失败消息
        return ApiResponseUtil.getApiResponse(ApiResponseEnum.LOGIN_FAIL);
    }

    @GetMapping("get_info")
    @ResponseBody
    public  ApiResponse chelogin(String token){
        System.out.println("进入控制器开始token:"+token);
        boolean verify = JwtUtil.verify(token);
        Map<String,String>map=new HashMap<>();
        map.put("shen","广州");
        map.put("shi","武汉");
        if(verify){
            return ApiResponseUtil.getApiResponse(map,200,ApiResponseEnum.SUCCESS.getErrMsg());
        }
        return ApiResponseUtil.getApiResponse(ApiResponseEnum.AUTH_ERROR);
    }


}
